package hu.myai.gui.widgets.panel;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

public class Panel extends Composite implements PaintListener {
    private int columns = 4;
    private int rows = 3;

    public Panel(Composite parent, int style) {
        super(parent, style | SWT.DOUBLE_BUFFERED);
        this.addPaintListener(this);
        this.setBackground(new Color(getDisplay(), 255, 128, 0));

        this.setLayout(new PanelLayout(this));
    }

    public Point getPosition(int c, int r) {
        int w = getSize().x / columns;
        int h = getSize().y / rows;

        int px = (int) (w * (c + 0.1));
        int py = (int) (h * (r + 0.1));

        return new Point(px, py);
    }

    public Point getSize(int w, int h) {
        int w0 = getSize().x / columns;
        int h0 = getSize().y / rows;

        int dx = (int) (w * w0 - w0 * 0.2);
        int dy = (int) (h * h0 - h0 * 0.2);

        return new Point(dx, dy);
    }

    @Override
    public void paintControl(PaintEvent e) {
        int w = e.width / columns;
        int h = e.height / rows;

        e.gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));

        for (Control c : getChildren()) {
            PanelData pd = (PanelData) c.getLayoutData();
            int px = (int) (w * (pd.x + 0.05));
            int py = (int) (h * (pd.y + 0.05));
            int dx = (int) (w * (pd.width - 0.1));
            int dy = (int) (h * (pd.height - 0.1));
            e.gc.fillRoundRectangle(px, py, dx, dy, (int) (w * 0.1), (int) (h * 0.1));
        }
    }

    public int getColumns() {
        return columns;
    }

    public void setColumns(int columns) {
        this.columns = columns;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }
}
